package cn.kgc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author 帅气逼人程序员
 * @version 1.0
 * @date 2023/3/2 - 19:34
 */
@Configuration
@EnableWebSecurity  //启用web安全框架，这里面的配置就可以替换原有配置
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true) //要求登录必须是post提交
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login")//设置登录路径,覆盖自带的原有方法
                .loginProcessingUrl("/doLogin")  // 登录的提交url路径
                .usernameParameter("userName")
                .passwordParameter("userPwd")
                .defaultSuccessUrl("/index",true)       //登录成功默认进入index首页
                .permitAll().and().authorizeRequests()
                .antMatchers("/login","/doLogin").permitAll()        // 这一些路径不需要验证，直接放行
                .anyRequest().authenticated()       //除开上面的请求，一律需要认证
                .and().csrf().disable();        //防攻击
        //403无权限跳转
        http.exceptionHandling().accessDeniedPage("/403");

    }

}
